<template v-if="bye">
  <a-config-provider prefix-cls="ss">
    <div class="smart-clip">
      <!-- 智能脚本工具头部 -->
      <div class="smart-clip-header">
        <div class="smart-clip-header-title_top">开始使用智能脚本工具</div>
        <div class="smart-clip-header-desc">
          在线化脚本编辑器，提供强大的智能写作能力，并有海量脚本模板提供创意辅助创作
        </div>
        <div class="smart-clip-header-btngroup">
          <a-tooltip v-if="!clipRole.includes('jbjj')" placement="topLeft">
            <template #title>
              <span>套餐不支持该权限</span>
            </template>
            <a-button :disabled="!clipRole.includes('jbjj')" type="primary"
              style="border: none; border-radius: 6px; margin-right: 20px"><plus-outlined
                :style="{ fontSize: '12px' }" />创建新脚本</a-button>
          </a-tooltip>

          <a-button v-if="clipRole.includes('jbjj')" @click="createHandle()" type="primary"
            style="border: none; border-radius: 6px; margin-right: 20px"><plus-outlined
              :style="{ fontSize: '12px' }" />创建新脚本</a-button>
        </div>
      </div>
      <!-- 我的脚本 -->
      <div class="smart-clip-content">
        <div class="smart-clip-header-title">我的脚本</div>
        <!-- 列表 -->
        <a-table :dataSource="myScriptDataList" :columns="columns" :pagination="myScriptpagination"
          @change="myScriptTableChange" :loading="loading" rowKey="id">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key == 'title'">
              <a-popover>
                <template #content v-if="record.title.trim().length > 20">
                  <div style="max-width: 120px; word-wrap: break-word">
                    {{ record.title }}
                  </div>
                </template>
                {{
                record.title.trim().length > 20
                ? `${record.title.substring(0, 30)}...`
                : record.title
                }}
              </a-popover>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <div class="action">
                <a-tooltip v-if="!clipRole.includes('jbjj')" placement="topLeft">
                  <template #title>
                    <span>套餐不支持该权限</span>
                  </template>
                  <a style="margin-right: 5px">编辑</a>
                </a-tooltip>
                <a v-if="clipRole.includes('jbjj')" @click="myScriptCreate(record.id)" style="margin-right: 5px">编辑</a>
                <a-tooltip v-if="!clipRole.includes('jbjj')" placement="topLeft">
                  <template #title>
                    <span>套餐不支持该权限</span>
                  </template>
                  <a style="margin-right: 5px">删除</a>
                </a-tooltip>
                <a @click="myScriptDelete(record.id, 'delete')" style="margin-left: 5px">删除</a>
              </div>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 脚本广场 -->
      <div class="smart-clip-content" style="margin-top: 0">
        <!-- 标题 -->
        <div class="smart-clip-header-title" style="margin-top: 0; padding: 0 0 8px 0">
          脚本广场
        </div>
        <!-- 列表--有数据-->
        <a-spin size="large" tip="加载中..." :spinning="spinning">
          <div class="script-list" v-if="squareList && squareList.length > 0">
            <div class="script-item" v-for="(item, index) in squareList" :key="index"
              @click="templateSquareCreateHandle(item)">
              <div style="background-color: #000">
                <img class="script-item-img" v-lazy="item.thumb_url || item.img" :src="item.thumb_url || item.img" />
              </div>
              <div class="script-item-info">
                <a-popover v-if="item.title && item.title.trim().length > 12">
                  <template #content>
                    <div style="max-width: 120px; word-wrap: break-word">
                      {{ item.title }}
                    </div>
                  </template>
                  <h6 class="script-item-title">
                    <span>
                      {{
                      item.title && item.title.trim().length > 19
                      ? `${item.title && item.title.substring(0, 18)}...`
                      : item.title
                      }}</span>
                  </h6>
                </a-popover>
                <h6 class="script-item-title" v-else>
                  <span>{{ item.title }}</span>
                </h6>
                <a-popover v-if="item.desc && item.desc.trim().length > 25">
                  <template #content>
                    <div style="max-width: 120px; word-wrap: break-word">
                      {{ item.desc }}
                    </div>
                  </template>
                  <div class="script-item-desc">
                    {{
                    item.desc && item.desc.trim().length > 50
                    ? `${item.desc && item.desc.substring(0, 50)}...`
                    : item.desc
                    }}
                  </div>
                </a-popover>
                <div class="script-item-desc" v-else>
                  {{ item.desc }}
                </div>
              </div>
            </div>
          </div>
        </a-spin>
        <!-- 列表--无数据 -->
        <div style="display: flex; justify-content: center; width: 100%" v-if="squareList && squareList.length <= 0">
          <a-empty />
        </div>
      </div>
      <!-- 创建脚本组件 -->
      <AuthoringScript ref="authoringScript" />
    </div>
    <!-- 充值弹窗 -->
    <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

  </a-config-provider>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  createVNode,
  onMounted,
} from "vue";

// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
import {
  PlusOutlined,
  SearchOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import AuthoringScript from "./modules/AuthoringScript.vue";
import { Modal, notification } from "ant-design-vue";
// 封装的请求
import request from "@/common/utils/request";
import { message } from "ant-design-vue";
import store from "@/store/index.js";
import { onBeforeRouteLeave } from "vue-router";

export default defineComponent({
  name: "ScriptingTool",
  components: {
    vipModal,
    PlusOutlined,
    SearchOutlined,
    EllipsisOutlined,
    AuthoringScript,
  },
  setup() {
    const router = useRouter();
    const vipVisible = ref(false)

    const state = reactive({
      bye: true,
      myScriptDataList: [], //我的脚本列表数据
      columns: [
        {
          title: "序号",
          align: "left",
          dataIndex: "id",
          key: "id",
          align: "center",
        },
        {
          title: "脚本名称",
          align: "left",
          dataIndex: "title",
          key: "title",
          align: "center",
        },
        {
          title: "场景数",
          align: "left",
          dataIndex: "scene_count",
          key: "scene_count",
          align: "center",
        },
        {
          title: "修改时间",
          dataIndex: "updated_at",
          key: "updated_at",
          align: "left",
          sorter: true,
          align: "center",
        },
        {
          title: "创建时间",
          dataIndex: "created_at",
          key: "created_at",
          align: "center",
          sorter: true,
        },
        {
          title: "操作",
          dataIndex: "action",
          key: "action",
          align: "center",
        },
      ],
      myScriptPageSize: 5, //我的脚本分页条数
      myScriptPage: 1, //我的脚本分页页码
      myScriptTotal: 0, //我的脚本分页总条数
      squareList: {}, //脚本广场列表
      squarePageSize: 15, //脚本广场分页条数
      squarePage: 1, //脚本广场分页页码
      squareTotal: 0, //脚本广场分页总条数
      authoringScript: null, //创建脚本组件实例
      spinning: false, //加载spining
      orderBys: {}, //是否开启排序
    });

    const clipRole = computed(() => store.state.user?.clipRole || []);

    // 我的脚本分页
    const myScriptpagination = computed(() => ({
      total: state.myScriptTotal,
      current: state.myScriptPage,
      pageSize: state.myScriptPageSize,
      showSizeChanger: false,
      size: "small",
      showTotal: (myScriptTotal) => `共${myScriptTotal}条`,
    }));

    // 我的脚本分页切换
    const myScriptTableChange = (pager, filter, sorter) => {
      if (sorter.column && sorter.column.key) {
        state.orderBys = {
          [sorter.column.key]: sorter.order,
        };
      }
      state.myScriptPage = pager.current;
      state.squarePageSize = pager.pageSize;
      getMyScriptLineList(); //重新获取我的脚本列表
    };

    /**
     * @description 获取我的脚本列表
     * @param {Number} pageSize 列表分页
     * @param {Number} page 列表分页
     * @param {String} title 脚本名称
     * @param {Number} type 类型 0-公共脚本，1-我的脚本，不传值默认为1
     * @param {Number} platform 适用平台（0-第三方平台，1-自有平台），不传值默认记为0
     */
    // 获取我的脚本列表
    const getMyScriptLineList = () => {
      state.loading = true;
      let params = {
        pageSize: state.myScriptPageSize,
        page: state.myScriptPage,
        title: "",
        type: 1,
        platform: 1,
        orderBys: state.orderBys,
      };
      request
        .get("/work_ai", "/user/shotstack/script-line/list", params)
        .then((res) => {
          state.myScriptDataList = res.list?.data;
          state.myScriptTotal = res.list?.total;
          console.log(state.myScriptDataList, "我的脚本列表");
        })
        .finally(() => { });
    };

    /**
     * @description 获取脚本广场数据列表
     * @param {Number} pageSize 列表分页
     * @param {Number} page 列表分页
     * @param {String} title 脚本名称
     * @param {Number} type 类型 0-公共脚本，1-我的脚本，不传值默认为1
     * @param {Number} platform 适用平台（0-第三方平台，1-自有平台），不传值默认记为0
     */
    // 获取脚本广场列表
    const getSquareScriptLineList = () => {
      state.spinning = true;
      let params = {
        pageSize: state.squarePageSize,
        page: state.squarePage,
        title: "",
        type: 0,
        platform: 1,
      };
      request
        .get("/work_ai", "/user/shotstack/script-line/list", params)
        .then((res) => {
          state.squareList = res.list?.data;
          state.squareTotal = res.list?.total;
          console.log(res, "模板广场列表");
          state.spinning = false;
        })
        .finally(() => {
          state.spinning = false;
        });
    };
    // 脚本广场分页change事件
    const squarePageChange = (page, pageSize) => {
      state.squarePage = page;
      state.squarePageSize = pageSize;
      getSquareScriptLineList(); //重新获取脚本广场列表
    };
    // 编辑我的脚本
    const squareCreateHandle = (id) => {
      router.push({
        path: "/ScriptSquare",
        query: { id: id },
      });
    };
    // 创建我的脚本
    const createHandle = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
       vipVisible.value = true
      } else {
        router.push({
          path: "/ScriptSquare",
        });
      }
    };
    // 编辑我的脚本
    const myScriptCreate = (id) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true
      } else {
        if (!clipRole.value.includes("jbjj")) {
          message.error("套餐不支持该权限");
        } else {
          router.push({
            path: "/ScriptSquare",
            query: { id: id },
          });
        }
      }
    };
    // 删除我的脚本
    const myScriptDelete = (id) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true
      } else {
        if (!clipRole.value.includes("jbjj")) {
          message.error("套餐不支持该权限");
        } else {
          Modal.confirm({
            title: () => `确定要删除吗？`,
            content: "",
            okText: "确认",
            cancelText: "取消",
            icon: () => createVNode(ExclamationCircleOutlined),
            centered: true,
            onOk() {
              request
                .del("/work_ai", "/user/shotstack/script-line/delete", {
                  scriptLineId: id,
                })
                .then((res) => {
                  if (res.result) {
                    message.success("删除成功");
                    getMyScriptLineList(); // 获取我的脚本列表
                  }
                });
            },
            onCancel: () => { },
          });
        }
      }
    };
    // 模板广场详情
    const templateSquareCreateHandle = (info) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true
      } else {
        if (!clipRole.value.includes("jbjj")) {
          message.error("套餐不支持该权限");
        } else {
          router.push({
            path: "/templateScriptSquare",
            query: {
              id: info.id,
            },
          });
        }
      }
    };
    onMounted(() => {
      getMyScriptLineList(); // 获取我的脚本列表
      getSquareScriptLineList(); //获取脚本广场列表
    });

    onBeforeRouteLeave((to, from, next) => {
      state.bye = false;
      next(true);
    });
    return {
      ...toRefs(state),
      vipVisible,
      myScriptTableChange,
      myScriptCreate,
      myScriptDelete,
      getMyScriptLineList,
      getSquareScriptLineList,
      squarePageChange,
      squareCreateHandle,
      createHandle,
      templateSquareCreateHandle,
      myScriptpagination,
      clipRole,
    };
  },
});
</script>

<style lang="less" scoped>
.smart-clip {
  padding: 14px 14px 0;
}

// 头部
.smart-clip-header {
  padding: 30px 30px 0;
  border-radius: 12px;
  height: 180px;
  min-width: 1140px;
  // margin-top: 20px;
  background: linear-gradient(220deg, #f3f7ff, rgba(159, 191, 255, 0.4));
  display: flex;
  flex-direction: column;

  .smart-clip-header-title_top {
    font-size: 24px;
    color: #0c0d0e;
    line-height: 1.5;
  }

  .smart-clip-header-desc {
    font-size: 14px;
    color: #737a87;
    margin-top: 5px;
    line-height: 1.5;
  }

  .smart-clip-header-btngroup {
    margin-top: 15px;
  }
}

// 主体
.smart-clip-content {
  padding: 10px 0 0;
  margin-top: 24px;
  min-width: 1140px;

  .smart_clip_content_pagination {
    display: flex;
    margin-top: 30px;
    justify-content: flex-end;
  }
}

// 标题
.smart-clip-header-title {
  font-size: 16px;
  padding: 8px 0;
  font-weight: 500;
  margin: 10px 0;
}

:deep(.ss-table-tbody > tr > td) {
  padding: 9px 10px !important;
}

:deep(.ss-table-thead > tr > th) {
  padding: 9px 10px !important;
}

:deep(.ss-table-body) {
  font-size: 12px;

  &::-webkit-scrollbar {
    width: 6px;
    background: #ffffff;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
}

.action {
  a {
    color: var(--ss-primary-color);
  }
}

// 脚本广场
.script-list {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 16px;
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;

  // 168, 168, 168
  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 10px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
  }

  &::-webkit-scrollbar-thumb {
    background: rgb(168, 168, 168);
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */
  }

  .script-item {
    width: 100%;
    margin-right: 15px;
    margin-bottom: 15px;
    border-radius: 5px;
    // border-radius: 5px 5px 0 0;
    overflow: hidden;
    cursor: pointer;
    background: #fff;
    border: 1px solid #eaedf1;

    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .script-item-img {
      width: 100%;
      height: 162px;
      border: none;
      object-fit: cover;
      vertical-align: middle;
    }

    .script-item-info {
      border-radius: 0 0 8px 8px;
      box-sizing: border-box;
      border-top: none;
      width: 100%;
      height: 109px;
      // padding: 5px;
      font-size: 16px;
      line-height: 1.5;
      padding: 8px 12px;

      // margin-bottom: 5px !important;
      .script-item-title {
        width: 100%;
        font-size: 16px;
        font-weight: 500;
        white-space: nowrap;
        /* 防止文本换行 */
        overflow: hidden;
        /* 隐藏溢出部分 */
        text-overflow: ellipsis;
        /* 使用省略号表示溢出部分 */
      }

      .script-item-desc {
        width: 100%;
        font-size: 14px;
        max-height: 42px;
        color: #737a87;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden; //溢出内容隐藏
        text-overflow: ellipsis; //文本溢出部分用省略号表示
        display: -webkit-box; //特别显示模式
        -webkit-line-clamp: 2; //行数
        line-clamp: 2;
        -webkit-box-orient: vertical; //盒子中内容竖直排列
      }
    }
  }
}

:deep(.ss-table-pagination.ss-pagination) {
  margin: 16px 0 10px 0 !important;
}
</style>
